﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace NWMES
{
    public static class XmlHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="Obj"></param>
        /// <param name="xmlfilepath"></param>
        public static void Serializer(Object Obj, string xmlfilepath)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(xmlfilepath))
                {
                    var xs = new XmlSerializer(Obj.GetType());
                    xs.Serialize(writer, Obj);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

        }


        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xmlfilepath"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xmlfilepath)
        {
            try
            {
                Type type = typeof(T);
                XmlSerializer serializer = new XmlSerializer(type);
                using (FileStream fs = new FileStream(xmlfilepath, FileMode.Open))
                {
                    return (T)serializer.Deserialize(fs);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return default;
            }

        }
    }
}
